%#!/usr/bin/env escript

-module(my_match).  
-export([start/2, processer/0]).

start (File, N) ->

	register (to_writer, spawn (fun () -> writer([]) end)),
	register (to_producer, spawn (fun () -> producer(File) end)),

	Process_list = [{X, spawn (fun processer/0)} || X <- lists:seq(0, N - 1)],
	Process_dict = dict:from_list (Process_list),

	to_producer ! {process_pid_dict, Process_dict}.

processer() ->
    receive
	{Line, Num} -> 

		Result = re:run (Line, "<title>(.*?)</title>", [{capture, [1], list}, unicode]),
		case Result of
			nomatch -> [];
			{match, Title} ->
				to_writer ! {title, Title, Num}
		end,
		
		New_result = re:run (Line, ".*?<redirect title=\"(.*?)\"", [{capture, [1], list}, unicode]),
		case New_result of
			nomatch -> [];
			{match, Redirect_title} ->
				to_writer ! {redirect, Redirect_title, Num}
		end,
			
	    processer()
    end.

send_message (Device, Pid_dict, Num) ->
	case io:get_line (Device, "") of
		eof -> file:close(Device);
		Line -> 
			Idx = Num rem (length (dict:to_list (Pid_dict))),
			dict:fetch (Idx, Pid_dict) ! {Line, Num},
			send_message (Device, Pid_dict, Num + 1)
	end.

writer (Last) ->
	receive
	{Tag, Message, Num} ->
		io:format("~ts~n", Message),
		writer()
	end.

producer (File) ->
	receive
	{process_pid_dict, Pid_dict} ->
		
		{ok, S} = file:open (File, [read, {encoding, unicode}]),
		send_message (S, Pid_dict, 0)

	end.
